<?php namespace App\Http\Controllers\Api;

use App\Exceptions\NotFoundException;
use App\Exceptions\SecurityException;
use App\Http\Requests\ChangeUserInfoRequest;
use App\Http\Requests\SignUpRequest;
use App\Http\Requests\UserCreateEditRequest;
use App\Http\Requests\UserTeamsRequest;
use App\InvestOrg;
use App\ProjectTeam;
use App\Services\UserManager;
use App\UserCreate;
use App\UserInfo;
use App\User;
use App\UserTeams;
use App\UserWork;
use Illuminate\Auth\Guard;
use Illuminate\Support\Facades\Input;
use App\Project;

class UserController extends ApiController
{
    public function EditUserInfo(Guard $guard,ChangeUserInfoRequest $request,$id){
        if($guard->guest())
            throw new SecurityException(SecurityException::LoginFirst);

        /** @var User  $currentUser */
        $currentUser = $guard->user();
        if(!$currentUser || $currentUser->id != $id)
            throw new SecurityException(SecurityException::NoPermission);

        /** @var User $user */
        $user = User::find($id);
        if(!$user)
            throw new NotFoundException(NotFoundException::UserNotFound);

        $userInfo = $user->userInfo;
        if(!$userInfo){
            $userInfo =  new UserInfo();
            $userInfo->toUser()->associate($user);
            $userInfo->save();
        }

        $realname   =   $request -> get('realname');        //用户名
        $user_id    =   $id;                                //用户ID
        $province   =   Input::get('province');             //省份
        $city       =   Input::get('city');                 //城市
        $town       =   Input::get('town');                 //区 县
        $wechat     =   $request -> get('wechat');          //微信
        $weibo      =   $request -> get('weibo');           //微博
        $maimai     =   $request -> get('maimai');          //脉脉
        $edu_school =   $request -> get('edu_school');      //毕业学校
        $position   =   $request -> get('position');        //职位
        $user_desc  =   $request -> get('user_desc');       //个人介绍
        $photo_id   =   $request -> get('photo_id');        //图片标识
        $email      =   $request -> get('email');           //邮箱
        $phone      =   $request -> get('phone');           //电话

        if(!is_null($realname))$userInfo->realname = $realname;
        if(!is_null($user_id))$userInfo->user_id = $user_id;
        if(!is_null($province))$userInfo->province = $province;
        if(!is_null($city))$userInfo->city = $city;
        if(!is_null($town))$userInfo->town = $town;
        if(!is_null($wechat))$userInfo->wechat = $wechat;
        if(!is_null($weibo))$userInfo->weibo = $weibo;
        if(!is_null($maimai))$userInfo->maimai = $maimai;
        if(!is_null($edu_school))$userInfo->edu_school = $edu_school;
        if(!is_null($position))$userInfo->position = $position;
        if(!is_null($user_desc))$userInfo->user_desc = $user_desc;
        if(!is_null($photo_id)) $userInfo->photo_id = $photo_id;

        $user = User::find($id);
        if(!is_null($email)) $user->email   = $email;
        if(!is_null($phone)) $user->phone   = $phone;

        $user->save();
        $userInfo->save();

        return $this->buildResponse(trans('api.user.edit_user_info.success'),$userInfo);
    }

    /**
     * 通过用户id获取用户头像
     * @param $userId
     * @return \Symfony\Component\HttpFoundation\BinaryFileResponse
     * @throws NotFoundException
     */
    public function getPhotoByUserId($userId)
    {
        $user = User::find($userId);
        $userInfo = UserInfo::whereUserId($userId)->first();

        if(!$userInfo)
            return \Response::download('images/default_photo.jpg','default_photo.jpg',[],'inline');

        if($userInfo->photo_id==0)
            return \Response::download('images/default_photo.jpg','default_photo.jpg',[],'inline');

        if(!$user)
            throw new NotFoundException(NotFoundException::UserNotFound);


        if(!$userInfo && $user)
            return \Response::download('images/default_photo.jpg','default_photo.jpg',[],'inline');

        $photo = $userInfo->toPhoto;
        if(!$photo || $photo == null)
            return \Response::download('images/default_photo.jpg','default_photo.jpg',[],'inline');

        $photoFile = $photo->files;

        if(!$photoFile || $photoFile == null)
            return \Response::download('images/default_photo.jpg','default_photo.jpg',[],'inline');

        return \Response::download($photoFile->getLocalPath(),$photoFile->file_name,[],'inline');
    }


    /**
     * 通过工作经历的logoId寻找项目图片
     * @param $logoId
     * @return mixed
     * @throws NotFoundException
     */
    public function getProjectLogoByLogoId($logoId)
    {
        $userWork = UserWork::whereLogoId($logoId)->first();
        if(!$userWork)
            throw new NotFoundException(NotFoundException::PhotoNotFound);

        $photo = $userWork->toProjectLogo;
        if(!$photo || $photo == null)
            return \Response::download('images/default_photo.jpg','default_photo.jpg',[],'inline');

        $photoFile = $photo->files;
        return \Response::download($photoFile->getLocalPath(),$photoFile->file_name,[],'inline');

    }

    /**
     * 通过用户id获取 用户身份证正面
     * @param $userId
     * @return \Symfony\Component\HttpFoundation\BinaryFileResponse
     * @throws NotFoundException
     */
    public function getCardFrontByUserId($userId)
    {
        $userInfo = UserInfo::whereUserId($userId)->first();

        if(!$userInfo)
            throw new NotFoundException(NotFoundException::UserNotFound);

        $cardFrontFile = $userInfo->toCardFront->files;

        if(!$cardFrontFile || $cardFrontFile == null)
            return \Response::download('images/default_photo,jpg','default_photo.jpg',[],'inline');

        return \Response::download($cardFrontFile->getLocalPath(),$cardFrontFile->file_name,[],'inline');
    }

    /**
     * 通过用户id获取用户身份证反面
     * @param $userId
     * @return \Symfony\Component\HttpFoundation\BinaryFileResponse
     * @throws NotFoundException
     */
    public function getCardBackByUserId($userId)
    {
        $userInfo = UserInfo::whereUserId($userId)->first();

        if(!$userInfo)
            throw new NotFoundException(NotFoundException::UserNotFound);

        $cardBackFile = $userInfo->toCardBack->files;

        if(!$cardBackFile || $cardBackFile == null)
            return \Response::download('images/default_photo,jpg','default_photo.jpg',[],'inline');

        return \Response::download($cardBackFile->getLocalPath(),$cardBackFile->file_name,[],'inline');
    }

    /**
     * 通过用户id获取用户名片
     * @param $userId
     * @return \Symfony\Component\HttpFoundation\BinaryFileResponse
     * @throws NotFoundException
     */
    public function getCallCardByUserId($userId)
    {
        $userInfo = UserInfo::whereUserId($userId)->first();

        if(!$userInfo)
            throw new NotFoundException(NotFoundException::UserNotFound);

        $callCardFile = $userInfo->toCallCard->files;

        if(!$callCardFile || $callCardFile == null)
            return \Response::download('images/default_photo,jpg','default_photo.jpg',[],'inline');

        return \Response::download($callCardFile->getLocalPath(),$callCardFile->file_name,[],'inline');
    }


    public function getOrgLogoByOrgId($orgId)
    {
        $investOrg = InvestOrg::find($orgId);
        if(!$investOrg)
            throw new NotFoundException(NotFoundException::PhotoNotFound);

        $photo = $investOrg->toOrgLogo;
        if(!$photo || $photo == null)
            return \Response::download('images/default_photo.jpg','default_photo.jpg',[],'inline');

        $photoFile = $photo->files;

        if(!$photoFile || $photoFile == null)
            return \Response::download('images/default_photo.jpg','default_photo.jpg',[],'inline');

        return \Response::download($photoFile->getLocalPath(),$photoFile->file_name,[],'inline');

    }

    /**
     * 用户信息填充（团队信息填充）
     * @param Guard $guard
     * @param UserTeamsRequest $request
     * @param int $id
     * @return \Illuminate\View\View|\Symfony\Component\HttpFoundation\Response
     * @throws SecurityException
     */
    public function EditUserTeams(Guard $guard , UserTeamsRequest $request , $id=0)
    {
        /** 判断用户是否登录*/
        if($guard->guest())
            throw new SecurityException(SecurityException::LoginFirst);

        /** @var User  $currentUser */
        $currentUser = $guard->user();
        if(!$currentUser)
            throw new SecurityException(SecurityException::NoPermission);

        if($id != 0 && UserTeams::whereId($id)->exists())
        {
            $UserTeams = UserTeams::find($id);
        }else{
            $UserTeams = new UserTeams();
        }
        if(!is_null($request->get('user_id'))) $UserTeams->user_id     = $request -> get('user_id');
        if(!is_null($request->get('realname'))) $UserTeams->real_name  = $request -> get('realname');
        if(!is_null($request->get('province'))) $UserTeams->province   = $request -> get('province');
        if(!is_null($request->get('city'))) $UserTeams->city           = $request -> get('city');
        if(!is_null($request->get('wechat'))) $UserTeams->wechat       = $request -> get('wechat');
        if(!is_null($request->get('weibo'))) $UserTeams->weibo         = $request -> get('weibo');
        if(!is_null($request->get('maimai'))) $UserTeams->maimai       = $request -> get('maimai');
        if(!is_null($request->get('school'))) $UserTeams->school       = $request -> get('school');
        if(!is_null($request->get('position'))) $UserTeams->position   = $request -> get('position');
        if(!is_null($request->get('team_desc'))) $UserTeams->profile   = $request -> get('team_desc');
        if(!is_null($request->get('photo_id'))) $UserTeams->photo_id   = $request -> get('photo_id');
        if(!is_null($request->get('is_founder'))) $UserTeams->is_founder   = $request -> get('is_founder');
        if(empty($UserTeams->is_founder)) $UserTeams->is_founder = 0 ;
        $UserTeams->status      = 0 ;
        $UserTeams->check_time  = date('Y-m-d',time());

        $UserTeams->save();
        $proId = $request->get('project_id');
        if($id==0)
            $UserTeams->project_x_team()->attach($proId);

        return $this->buildResponse(trans('api.edit-user_teams.success'), $UserTeams);
    }


    /**
     * 编辑用户创业经历信息
     *
     * @param Guard $guard
     * @param UserCreateEditRequest $request
     * @param int $id
     * @return \Illuminate\View\View|\Symfony\Component\HttpFoundation\Response
     * @throws SecurityException
     */
    public function EditUserCreate(Guard $guard , UserCreateEditRequest $request , $id=0)
    {
        /** 判断用户是否登录*/
        if($guard->guest())
            throw new SecurityException(SecurityException::LoginFirst);

        /** @var User  $currentUser */
        $currentUser = $guard->user();
        if(!$currentUser)
            throw new SecurityException(SecurityException::NoPermission);

        if($id != 0 && UserCreate::whereId($id)->exists()){
            $UserCreate = UserCreate::find($id);

        }else{
            $UserCreate = new UserCreate();
        }

        if(!is_null($request->get('user_id'))) $UserCreate->user_id = $request->get('user_id');
        if(!is_null($request->get('company'))) $UserCreate->company = $request->get('company');
        if(!is_null($request->get('position'))) $UserCreate->position = $request->get('position');
        if(!is_null($request->get('start_time'))) $UserCreate->start_time = $request->get('start_time');
        if(!is_null($request->get('end_time'))) $UserCreate->end_time = $request->get('end_time');
        if(!is_null($request->get('check_time'))) $UserCreate->check_time = date('Y-m-d H:i:s' , time());
        if(!is_null($request->get('status'))) $UserCreate->status = 0 ;
        $UserCreate->save();

        return $this->buildResponse(trans('api.edit-user-create.success') , $UserCreate );
    }

    /**
     * 编辑用户工作经历信息
     *
     * @param Guard $guard
     * @param UserCreateEditRequest $request
     * @param int $id
     * @return \Illuminate\View\View|\Symfony\Component\HttpFoundation\Response
     * @throws SecurityException
     */
    public function EditUserWork(Guard $guard , UserCreateEditRequest $request , $id=0)
    {
        /** 判断用户是否登录*/
        if($guard->guest())
            throw new SecurityException(SecurityException::LoginFirst);

        /** @var User  $currentUser */
        $currentUser = $guard->user();
        if(!$currentUser)
            throw new SecurityException(SecurityException::NoPermission);

        if($id != 0 && UserWork::whereId($id)->exists()){
            $UserWork = UserWork::find($id);

        }else{
            $UserWork = new UserWork();
        }

        if(!is_null($request->get('user_id'))) $UserWork->user_id = $request->get('user_id');
        if(!is_null($request->get('company'))) $UserWork->company = $request->get('company');
        if(!is_null($request->get('position'))) $UserWork->position = $request->get('position');
        if(!is_null($request->get('start_time'))) $UserWork->start_time = $request->get('start_time');
        if(!is_null($request->get('end_time'))) $UserWork->end_time = $request->get('end_time');
        if(!is_null($request->get('check_time'))) $UserWork->check_time = date('Y-m-d H:i:s' , time());
        if(!is_null($request->get('status'))) $UserWork->status = 0 ;
        $UserWork->save();

        return $this->buildResponse(trans('api.edit-user-work.success') , $UserWork );
    }

    public function doCreateUser(SignUpRequest $request)
    {
        $username = $request->get('username');
        $email    = $request->get('email');
        $phone    = $request->get('phone');
        $password = $request->get('password');
        $role     = $request->get('role');

        $user = UserManager::signUp($username,$email,$phone,$password,$role);
        $user ->save();

        return $this->buildResponse(trans('api.user.create.success'), $user);
    }


    /**
     * 获取更多的创业者信息
     * @return bool|\Illuminate\View\View|\Symfony\Component\HttpFoundation\Response
     */
    public function getCreaterMore()
    {
        $counts     = User::whereRole(0)->whereStatus(1)->count('id');      /** 总记录数 */
        $page       = Input::get('page');                                   /** 页数 */
        $offset     = 0;
        if($page != 0 )
            $offset     = $page * self::PAGE ;

        if($counts >= $offset){
            $users   = User::whereRole(0)->whereStatus(1)->skip($offset)->take(self::PAGE)->get();
            if(!$users) return false;

            foreach($users as $user)
            {
                $user['userInfo'] = $user->userInfo;
                $user['position'] = $user->getUserworkByUserId($user->id);
            }

            return $this->buildResponse(trans('api.get_creater_more.success'),$users);
        }
    }


    public function getCreaterMessageBySearch()
    {
        $keyword    = Input::get('keyword');
        $dist       = Input::get('dist');
        $role       = Input::get('role');

        $users      = User::whereStatus(1);

        if(!empty($role)){
            $users -> join('user_roles' , 'user_roles.user_id' , '=' , 'users.id');
            $users -> join('role' , 'role.id' , '=' , 'user_roles.role_id');
            $users -> where('role.id' , '=' , $role);
        }

        if(!empty($dist)){
            $users -> join('user_info' , 'user_info.user_id' , '=' , 'users.id');
            $users -> where('user_info.province', 'like', '%'.$dist.'%');
        }

        if(!empty($keyword)){
            $users -> join('user_info', 'user_info.user_id' , '=' , 'users.id');
            $users -> orWhere('user_info.realname' , 'like' , "%$keyword%");
            $users -> orWhere('user_info.user_desc' , 'like' , "%$keyword%");
        }

        $users  = $users -> where('users.role' , '', 0) -> get() ;
        if(!$users) return false;

        foreach($users as $user)
        {
            $user['userInfo'] = $user->userInfo;
            $user['position'] = $user->getUserworkByUserId($user->id);
        }
        return $this->buildResponse(trans('api.get_creater_more.success'),$users);
    }

    /**
     * 通过创业经历标志删除创业经历
     * @param Guard $guard
     * @return \Illuminate\View\View|\Symfony\Component\HttpFoundation\Response
     * @throws SecurityException
     * @throws \Exception
     */
    public function DelUserCreateById(Guard $guard)
    {
        /** 判断用户是否登录*/
        if($guard->guest())
            throw new SecurityException(SecurityException::LoginFirst);

        /** @var User  $currentUser */
        $currentUser = $guard->user();
        if(!$currentUser)
            throw new SecurityException(SecurityException::NoPermission);

        $userCreateId = Input::get('userCreateId'); file_put_contents('E:/1.log' , $userCreateId);
        $res = UserCreate::find($userCreateId)->delete();
        return $this->buildResponse(trans('api.del_user_create.success'));

    }

    /**
     * 通过工作经历标志删除工作经历
     * @param Guard $guard
     * @return \Illuminate\View\View|\Symfony\Component\HttpFoundation\Response
     * @throws SecurityException
     * @throws \Exception
     */
    public function DelUserWorkById(Guard $guard)
    {
        /** 判断用户是否登录*/
        if($guard->guest())
            throw new SecurityException(SecurityException::LoginFirst);

        /** @var User  $currentUser */
        $currentUser = $guard->user();
        if(!$currentUser)
            throw new SecurityException(SecurityException::NoPermission);

        $userWorkId = Input::get('userWorkId');
         $res = UserWork::find($userWorkId)->delete();
        return $this->buildResponse(trans('api.del_user_work.success'));
    }


}